// controllers/purchaseOrderController.js
const PurchaseOrder = require('../models/purchaseOrderModel');

const purchaseOrderController = {
    async getAll(req, res) {
        try {
            const orders = await PurchaseOrder.getAll();
            res.json({ code: 200, data: orders });
        } catch (error) {
            console.error(error);
            res.status(500).json({ code: 500, message: '服务器错误' });
        }
    },

    async getById(req, res) {
        try {
            const { id } = req.params;
            const order = await PurchaseOrder.getById(id);
            if (!order) return res.status(404).json({ code: 404, message: '未找到该采购单' });
            res.json({ code: 200, data: order });
        } catch (error) {
            console.error(error);
            res.status(500).json({ code: 500, message: '服务器错误' });
        }
    },

    async create(req, res) {
        try {
            const { name, numbering, purchaser, project, total_cost } = req.body;
            const result = await PurchaseOrder.create({ name, numbering, purchaser, project, total_cost });
            res.json({ code: 200, message: '创建成功', data: result });
        } catch (error) {
            console.error(error);
            res.status(500).json({ code: 500, message: '服务器错误' });
        }
    },

    async update(req, res) {
        try {
            const { id } = req.params;
            const success = await PurchaseOrder.update(id, req.body);
            if (!success) return res.status(404).json({ code: 404, message: '未找到该采购单' });
            res.json({ code: 200, message: '更新成功' });
        } catch (error) {
            console.error(error);
            res.status(500).json({ code: 500, message: '服务器错误' });
        }
    },


    async delete(req, res) {
        try {
            const { id } = req.params;
            const success = await PurchaseOrder.delete(id);
            if (!success) return res.status(404).json({ code: 404, message: '未找到该采购单' });
            res.json({ code: 200, message: '删除成功' });
        } catch (error) {
            console.error(error);
            res.status(500).json({ code: 500, message: '服务器错误' });
        }
    },
};

module.exports = purchaseOrderController;
